package com.example.sharding.demo.utils;

import io.shardingsphere.core.keygen.DefaultKeyGenerator;

import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

public class ParaseShardingKeyTool {

    private static DateTimeFormatter yearMonth =  DateTimeFormatter.ofPattern("yyyyMM");
    private static  DateTimeFormatter year = DateTimeFormatter.ofPattern("yyyy");


    public static String generateKey(){
        return getYearAndMonth(Long.valueOf(new DefaultKeyGenerator().generateKey()+""));
    }

    public static String getYearAndMonth(long shardingKey){
        Instant instant =  Instant.ofEpochMilli(DefaultKeyGenerator.EPOCH+(Long.valueOf(shardingKey+"")>>22));
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
        return  yearMonth.format(localDateTime);
    }

    public static String getYear(long shardingKey){
        Instant instant =  Instant.ofEpochMilli(DefaultKeyGenerator.EPOCH+(Long.valueOf(shardingKey+"")>>22));
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
        return  year.format(localDateTime);
    }

    /*public static void main(String[] args) {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMM");
        System.out.println(">>>>>>>>>"+simpleDateFormat.format(System.currentTimeMillis()));

        DefaultKeyGenerator defaultKeyGenerator = new DefaultKeyGenerator();
        System.out.println(">>>>>>>>>"+defaultKeyGenerator.generateKey());

        System.out.println(">>>>>>>>>"+ParaseShardingKeyTool.getYearAndMonth(Long.valueOf(defaultKeyGenerator.generateKey()+"")));
        System.out.println(">>>>>>>>>"+ParaseShardingKeyTool.getYearAndMonth(Long.valueOf(defaultKeyGenerator.generateKey()+"")));

        System.out.println(">>>>>>>>>"+ generateKey());
    }*/

}
